$(function (){


    //-------------------------------业务函数begin--------------------------------------------------------


    Date.prototype.format = function(format)
    {
        var o = {
            "M+" : this.getMonth()+1, //month
            "d+" : this.getDate(),    //day
            "h+" : this.getHours(),   //hour
            "m+" : this.getMinutes(), //minute
            "s+" : this.getSeconds(), //second
            "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
            "S" : this.getMilliseconds() //millisecond
        }
        if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
            (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)if(new RegExp("("+ k +")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length==1 ? o[k] :
                    ("00"+ o[k]).substr((""+ o[k]).length));
        return format;
    }

    //微信用户登录，强制登录型
    login()
    //微信验证登录并设置分享
    wxSDK().then(res=>{
        SDKyanzheng(res).then(res=>{
            let title = document.title
            let url = location.href
            let imgUrl=$('#zhandianIcon').attr('href')
            let desc='我的24 现场24 CH24'
            fenxiang(title,url,imgUrl,desc)
        })
    }).catch(error=>{
        console.log(error)
    })

    const form = layui.form;
    const layer = layui.layer;
    const cloud = wxCloud.cloud()
    const db = wxCloud.db()
    const flow = layui.flow;
    /**
     * 当前用户信息的全局变量
     * @type {string}
     */
    let userInfostr =  lsa.get('userInfo')
    console.log(userInfostr)
    /**
     * 话题弹窗的全局变量
     * @type {null}
     */
    let editHeaper = null
    /**
     * 当前用户的openid全局变量
     */
    let openid_test
    let heaperType='huati'
    /**
     * 评论ID全局变量
     */
    let currPinglunId

    // openid_test = JSON.parse(userInfostr).openid//'oW2Wk1ZO8fcIqbmJLir5oztTZxvA'

    // openid_test = 'oW2Wk1ZO8fcIqbmJLir5oztTZxvA'



    // testdb()

    async function  testdb(){


        let ta = await cloud.callFunction({
            name:'getJianyiItems',
            data:{page:1,limit:10,openid:lsa.get("openid"),selectAll:false}
        })
        console.log(ta.result);

    }



    /**
     * 调取数据库列表进行页面渲染
     */

    /**
     * 话题
     * 弹窗打开
     */
    $("#heaper").on('click',function (){

        $("#heper_title").text('话题：')
        heaperType='huati'

        if(userInfostr==null) {
            layer.msg("请在微信内打开并授权登录，在提交信息！")
            // return
        }

        editHeaper = layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            shadeClose: true,
            skin: 'yourclass',
            content: $("#form")
        });


    })

    /**
     * 提交建议事件
     */
    $("#submit").on("click", async function (){
        let msg
        let userInfostr =  lsa.get('userInfo')
        let userInfo = JSON.parse(userInfostr)
        let context = $("#yijiantext").val()
        //判断反馈信息是否为空
        if(context==""){
            layer.msg("请填入要反馈的信息。")
            return
        }
        let nowDate = new Date().format('yyyy-MM-dd hh:ss:mm')

        userInfo['context'] = context
        userInfo['state'] = ''
        userInfo['time'] = Date.now()
        userInfo['formatDate'] = new Date().format('yyyy-MM-dd hh:ss:mm')

        if(heaperType=='huati'){
            //判断当天内提交了多少次
            let reg = new RegExp(nowDate.split(' ')[0] + " \\d{2}:\\d{2}:\\d{2}",'g')
            let dayCount = await db.collection('jianyi').where({
                openid: lsa.get("openid"),
                formatDate:reg,
                pinglunId:0,
            }).count()

            if(dayCount.total>=3){
                layer.msg("当日提议不能超过三次")
                return
            }
            //判断30分钟有没有提交建议
            let timeCount = await db.collection('jianyi').where({
                openid:lsa.get("openid"),pinglunId:0,
            }).field({time:true,_id:false}).orderBy('time','desc').limit(1).get()
            let lastTime
            if(timeCount.data.length>0){
                lastTime = timeCount.data[0].time
                let cha = Date.now() - lastTime
                if((cha<=1800000)){
                    layer.msg("请在"+ Math.round((1800000 - cha)/60000)+ "分钟后在次提交内容")
                    return
                }
            }
            userInfo['pinglunId'] = 0
            msg = "提交成功"

        }else if(heaperType=='pinglun'){

            userInfo['pinglunId'] = currPinglunId
            msg = "评论成功"
        }

        db.collection('jianyi').add({data:userInfo})
        .then(res=>{

            if(res.errMsg=="collection.add:ok"){
                layer.msg(msg)
                if(heaperType=='pinglun'){
                    reloadFlowPingLun()

                }
                reloadFlow(true)


            }else{
                layer.msg("系统发生错误")
            }
            setTimeout(()=>{layer.closeAll()},1000)

        })
        .catch(e=>{

            layer.msg("系统发生错误")

            setTimeout(()=>{layer.closeAll()},1000)
        })

    })


    /**
     * 查看我的点击事件
     */
    $("#lookme").click('click',async function (){
        if(userInfostr==null) {
            layer.msg("请在微信内打开并授权登录")
            return
        }
        reloadFlow(false)
    })
    $("#lookall").click('click',function (){
        if(userInfostr==null) {
            layer.msg("请在微信内打开并授权登录")
            return
        }
        reloadFlow(true)
    })
    /**
     * 瀑布流列表初始化
     */
    reloadFlow(true)


    /**
     * 点赞事件
     */
    $("#list").on('click','div[data-rel=\'zan\']',async function (){


        let nowDate = new Date().format('yyyy-MM-dd hh:ss:mm')

        let userInfo = JSON.parse(userInfostr)

        let info = {
            formatDate:nowDate,
            time:Date.now(),
            openid:lsa.get("openid"),//userInfo.openid,
            zanyangId:this.dataset.id
        }

        let res
        let numel = $(this).parent()[0].nextSibling.nextSibling
        if($(this).attr('class')=='icon-zan'){

            try{
                res = await db.collection('dianzan').add({data:info})
            }catch (e) {
                console.log(e);
                layer.msg("系统错误")
                return
            }
            $(this).attr('class','icon-zan-hong')
            let curNum = parseInt(numel.innerText)
            numel.innerText = curNum + 1

        }else{

            try{
                res = await db.collection('dianzan').where({openid:lsa.get("openid")}).remove() //userInfo.openid
            }catch (e) {
                console.log(e);
                layer.msg("系统错误")
                return
            }
            $(this).attr('class','icon-zan')
            numel.innerText-=1
        }

        console.log(res);

    })

    /**
     *点击评论事件打开盒子
     */
    $("#list").on('click','div[data-rel=\'pinglun\']',async function (){
        currPinglunId = this.dataset.id
        $(".pinglun_box").show()
        $(".pinglun_box").animate({top:'0px'})

        $(".zhezhao").show()
        reloadFlowPingLun()

    })
    /**
     * //收起评论夹
     */

    $(".pinglun_box").on('click',function (e){
        $(this).animate({top:'100%'})
        $(".zhezhao").hide()
        $(".pinglun_box").hide()
    })
    //禁止冒泡
    $(".container_pinglun").on('click',function (e){
       e.stopPropagation()
    })
    /**
     * 打开评价编辑弹窗的事件
     */
    $("#inputPl").on('click',function (e){
        e.stopPropagation()
        $("#heper_title").text('评论：')
        heaperType='pinglun'
        editHeaper = layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            shadeClose: true,
            skin: 'yourclass',
            content: $("#form")
        });

    })


    /**
     * 建议列表初始化和重载的函数
     * @parms selectAll{布尔值}
     */
    function reloadFlow(selectAll){

        $('#list').html('')
        flow.load({
            elem: '#list' //指定列表容器
            ,done: async function(page, next){ //到达临界点（默认滚动触发），触发下一页
                let lis = []
                let skip = (page-1)*10
                cloud.callFunction({
                    name:'getJianyiItems',
                    data:{page,limit:10,openid:lsa.get("openid"),selectAll}
                }).then(res=>{
                    console.log(res.result);

                    let list = res.result.list
                    let pagetotal = Math.floor(res.result.total / 10)
                    console.log('pagetotal=>',pagetotal)
                    layui.each(list, function(index, item){
                        // console.log(item);
                        let date = new Date(item.time)
                        $lis = `
                                <li>
                                    <div class="card" >
                                        <div class="card-body">
                                            <div style="display: flex;align-items:center;justify-items: center;">
                                                <div class="card-title mr-2 text-info">${item.nickname}</div>
                                                <div class="card-title">${date.format("yyyy-MM-dd hh:mm:ss")}</div>
                                            </div>
                                            
                                             <div style="display: flex;align-items: flex-start;justify-items: center;">
                                                <div class="card-subtitle mt-2 mb-2 mr-2 text-muted">
                                                    <div class="headerImg">
                                                        <img src="${item.headimgurl}" class="img-fluid" alt="">
                                                    </div>
                                                </div>
                                                <div class="card-text mb-1 ">
                                                    ${item.context}
                                                </div>
                                            </div>
                                            
                                            <a href="#" class="card-link text-danger">${item.state}</a>
                                        </div>
                                        <div class="card-footer">
                                            <div class="fankui_box">
                                                <div class="pinglun">
                                                    <div class="icon"  data-rel="pinglun" data-id="${item._id}"><i class="iconfont icon-pinglun" ></i></div>
                                                    <div class="number">${item.pinglunCount}</div>
                                                </div>
                                                <div class="zan">
                                                    <div class="icon" ><div class="${item.mecount?'icon-zan-hong':'icon-zan'}" data-rel="zan" data-id="${item._id}"></div></div>
                                                    <div class="number">${item.zanCount}</div>
                                                </div>
                    
                                            </div>
                                        </div>
                                    </div>
                                </li>
                    `
                        $li ="<li>"+item._id+"</li>"
                        lis.push($lis);
                    });

                    next(lis.join(""), page <= pagetotal );

                })
            }
        });

    }

    /**
     * 这个是评论的列表更新函数
     */
    function reloadFlowPingLun(){
        $('.pl_list').html('')
        flow.load({
            elem: '.pl_list' //指定列表容器
            ,done: async function(page, next){ //到达临界点（默认滚动触发），触发下一页
                let lis = []
                let skip = (page-1)*10
                let count = await db.collection('jianyi').where({pinglunId:currPinglunId}).count()
                let total = count.total
                db.collection('jianyi')
                .where({pinglunId:currPinglunId})
                .limit(10)
                .skip(skip)
                .orderBy("time","desc")
                .get()
                .then(res=>{
                    console.log(res);
                    console.log(res.data);
                    let list = res.data
                    let pagetotal = Math.floor(total / 10)
                    console.log('pagetotal=>',pagetotal)
                    layui.each(list, function(index, item){
                        // console.log(item);
                        let date = new Date(item.time)

                        $li = `
                            <li>
                                <div class="card mb-2" >
                                    <div class="card-body">
                                        <div style="display: flex;align-items:center;justify-items: center;">
                                            <div class="card-title mr-2 text-info  text-wrap">${item.nickname}</div>
                                        </div>
                                        <div style="display: flex;align-items: flex-start;justify-items: center;">
                                            <div class="card-subtitle mt-2 mb-2 mr-2 text-muted">
                                                <div class="pl_headerImg">
                                                    <img src="${item.headimgurl}" class="img-fluid" alt="">
                                                </div>
                                            </div>
                                            <div class="card-text mb-1 ">
                                                ${item.context}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </li>`

                        lis.push($li);
                    });

                    next(lis.join(""), page <= pagetotal );
                })
                .catch(err=>{
                    console.log(err);
                })


            }
        });
    }


//-------------------------------功能函数end--------------------------------------------------------




})
